package com.lzx.adx.report.controller.v1.wifi;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.lzs.adx.commmon.utils.JsonUtils;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.bean.mapper.ReportMapper;
import com.lzx.adx.report.cache.AccountLocalCache;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.model.wifi.WifiRequest;
import com.lzx.adx.report.service.ReportService;
import com.lzx.adx.report.util.UrlUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RequestMapping("/wifi/hh")
@RestController
@Slf4j
@RequiredArgsConstructor
public class WifiHhController {


    @Autowired
    private ReportService reportService;

    @Autowired
    private ThreadPoolTaskExecutor reportExecutor;

    @Autowired
    private ReportMapper reportMapper;


    @GetMapping("/report")
    public ResponseEntity report(WifiRequest wifiRequest, HttpServletRequest request) {
        log.info("接收到wifi-优酷辉煌明天的请求参数为{}", JsonUtils.toJsonString(wifiRequest));
        //1.收到监测的数据存储
        ReportDTO reportDTO = reportMapper.toReportDTO(wifiRequest);
        reportDTO.setBizRequestId(IdUtil.fastSimpleUUID()+reportDTO.getDspId());
        reportDTO.setCreateTime(new Date());
        reportDTO.setUpdateTime(new Date());
        reportDTO.setExtend(JsonUtils.toJsonString(wifiRequest));
        reportDTO.setTraceTime(String.valueOf(System.currentTimeMillis() / 1000));
        reportExecutor.execute(() -> {
            reportService.saveData(reportDTO);
        });
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(wifiRequest.getDspId());
        String resultUrl = UrlUtil.covertHHUrl(accountDTO, reportDTO);
        log.info("账号id{}wifi-优酷辉煌明天请求的url为{}", wifiRequest.getDspId(), resultUrl);
        String result = HttpUtil.get(resultUrl);
        log.info("账号id{}wifi-优酷辉煌明天响应的结果为{}", wifiRequest.getDspId(), result);
        return ResponseEntity.ok(new Result());
    }


    /**
     * 伊对的回传
     *
     * @param requestId 请求参数
     * @return ResponseEntity
     * @throws Exception
     */
    @GetMapping("/yk/callback")
    public ResponseEntity ykCallBackUrl(String requestId, String event_type) throws Exception {
        log.info("头条收到了优酷辉煌明天回调wifi信息请求流水号{},回调类型为{}", requestId, event_type);
        if (StringUtils.isBlank(requestId)) {
            log.error("收到了优酷辉煌明天回调wifi信息请求流水号空");
            return ResponseEntity.ok(new Result());
        }
        if (StringUtils.isBlank(event_type)) {
            log.info("请求流水号{},收到了优酷辉煌明天回调wifi信息回调类型为空，不做回传", requestId);
            return ResponseEntity.ok(new Result());
        }
        if (!"0".equals(event_type)) {
            log.info("请求流水号{},收到了优酷辉煌明天回调wifi信息回调类型为空，回调类型为{}，不是激活，不做回传", requestId, event_type);
            return ResponseEntity.ok(new Result());
        }
        Map<String, Object> params = new HashMap<>();
        params.put("bizRequestId", requestId);
        List<ReportDTO> list = reportService.list(params);
        ReportDTO reportDTO;
        if (CollectionUtil.isNotEmpty(list)) {
            reportDTO = list.get(0);
            reportDTO.setResultType(event_type);
            reportDTO.setResultTime(String.valueOf(System.currentTimeMillis()));
            reportDTO.setUpdateTime(new Date());
            reportService.updateData(reportDTO,event_type);
        } else {
            log.error("当前流水号，系统当前不存在");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        //2.从缓存加载配置
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(reportDTO.getDspId());
        JSONObject jsonObject = JSONObject.parseObject(accountDTO.getSspExtend());
        String clientId = jsonObject.getString("clientid");
        WifiRequest wifiRequest = JsonUtils.parseObject(reportDTO.getExtend(), WifiRequest.class);
        Map<String, Object> paramsReq = new HashMap<>();
        paramsReq.put("cid", wifiRequest.getContentId());
        paramsReq.put("sid", wifiRequest.getSid());
        paramsReq.put("stime", wifiRequest.getStime());
        paramsReq.put("os", wifiRequest.getOs());
        paramsReq.put("idfa", wifiRequest.getIdfaMd5());
        paramsReq.put("mac", wifiRequest.getMacMd5());
        paramsReq.put("imei", wifiRequest.getImeiMd5());
        paramsReq.put("clientid", clientId);
        paramsReq.put("ts", System.currentTimeMillis() / 1000);
        paramsReq.put("event_type", "1");
        //将参数转换 进行排序转换为url
        String urlParams = UrlUtil.covertParamsOrderByAsc(paramsReq);
        String finalResultUrl = accountDTO.getSspApiUrl() + "?" + urlParams;
        String sign = StringUtils.upperCase(SecureUtil.md5(finalResultUrl + accountDTO.getSspKey()));
        String resultUrl = UrlUtil.handMeitu(finalResultUrl, sign);
        log.info("账号id{}请求流水号{} clientId{}优酷辉煌明天给wifi报回传结果，完整的URl{}", reportDTO.getDspId(), requestId, clientId, finalResultUrl);
        HttpRequest body = HttpUtil.createGet(resultUrl);
        String result = body.execute().body();
        log.info("账号id{}请求流水号{} clientId{}优酷辉煌明天给wifi报回传结果为{}", reportDTO.getDspId(), requestId, clientId, result);
        return ResponseEntity.ok(new Result());
    }


}
